/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ucjava.chat.commserve.rmi.common;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 *
 * This Singleton class exists in order to find
 * the IP address of the machine on which it's running.
 * 
 * The setIP() method is separate from the constructor because
 * it might get called independently, in cases where our
 * host's IP might have changed during program run.
 * 
 * @author tony
 */
public class OwnIP
{

    private String returnIP = null;
    private static OwnIP oneAndOnly = null;
    
    public String getIP() { return returnIP; }
    
    /**
     * From:
     * http://stackoverflow.com/questions/
     *  8765578/get-local-ip-address-without-connecting-to-the-internet
     * 
     * @throws SocketException 
     */
    public void setIP() throws SocketException
    {
        Enumeration<NetworkInterface> interfaces  = NetworkInterface.getNetworkInterfaces();
        
        while (interfaces.hasMoreElements())
          {
            NetworkInterface current = interfaces.nextElement();
            // skip virtual or loopback interface, or interface
            // that is down.
            if (!current.isUp() || current.isLoopback()
                    || current.isVirtual())
              {
                continue;
              }
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements())
              {
                InetAddress current_addr = addresses.nextElement();
                // skip IPV6 or loopback address:
                if (current_addr instanceof Inet6Address) { continue; }
                if (current_addr.isLoopbackAddress()) { continue; }
                returnIP = current_addr.getHostAddress();
              }
          }
    } // end setIP
    /*
     * Constructor method for the OwnIP Class. 
     */
    private OwnIP() throws SocketException
    {
        setIP();
    }
    
    
    public static OwnIP buildOwnIP() throws SocketException
    {
        if (oneAndOnly == null)
          {
            oneAndOnly = new OwnIP();
          }
        return oneAndOnly;
    }

    
} // end class OwnIP
